<template>
  <button @click="$router.go(-1)">返回</button>
  <button @click="$router.push('/navigation-before/aaa')">路由参数变化</button>

  <div>导航之前获取数据</div>

  <div style="margin: 20px;font-weight: bold">
    <div v-if="loading" style="color: grey">加载中...</div>
    <div v-else style="color: pink">获取数据成功</div>
  </div>
</template>

<script>
import {defineComponent} from 'vue';

export default defineComponent({
  name: 'NavigationBefore',
  beforeRouteEnter(to, from, next) {
    // 向服务端发送获取数据请求，但此处无法使用this

    // setTimeout相当于向后端服务器获取数据的请求
    setTimeout(() => {
      next(vm => vm.loading = false);
    }, 3000);
  },
  beforeRouteUpdate() {
    // 监听路由参数变化，向服务端发送获取数据请求
    this.mockServerGetData();
  },
  data() {
    return {
      loading: true
    };
  },
  methods: {
    mockServerGetData() {
      this.loading = true;

      // setTimeout相当于向后端服务器获取数据的请求
      setTimeout(() => {
        this.loading = false;
      }, 3000);
    }
  },
});
</script>

<style scoped>
button {
  margin-right: 10px;
  margin-bottom: 20px;
}
</style>